<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" name="InterviewModal" setup>
  import { ref, unref, defineEmits } from 'vue'
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './interview.data'
  import { computed } from '@vue/reactivity';
  import { save } from './interview.api'
  import { message } from 'ant-design-vue';

  const isUpdate = ref(true)

  const emit = defineEmits(['success'])

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'))
  let formData = {}

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async data => {
    resetFields()
    setModalProps({ confirmLoading: false })
    isUpdate.value = !!data?.isUpdate

    if (unref(isUpdate)) {
      formData = { ...data.record }
      setFieldsValue({
        ...data.record
      })
    }
  })

  async function handleSubmit() {
    try {
      const values = await validate()
      Object.assign(formData, values)
      setModalProps({ confirmLoading: true})
      // TODO custom api
      const { saved } = await save(formData, isUpdate.value)
      if (saved) {
        closeModal()
        emit('success')
      } else {
        message.error('失败')
      }
    } finally {
      setModalProps({ confirmLoading: false })
    }
  }
</script>
